//
//  UniversityDetailViewController.m
//  大学详情页面
//
//  Created by 唐秦崴 on 15/3/16.
//  Copyright (c) 2015年 Lizzy. All rights reserved.
//

#import "UniversityDetailViewController.h"
#import "MajorListViewController.h"

@interface UniversityDetailViewController () < UITableViewDelegate, UITableViewDataSource >
@property (weak, nonatomic) IBOutlet UIView *descripitonView;  // 简介视图
@property (weak, nonatomic) IBOutlet UIView *unitsView;
@property (weak, nonatomic) IBOutlet UITableView *unitTableView;
@property (strong, nonatomic) IBOutlet UIImageView *universityImageView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicator; // 加载待显示图标
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITextView *universityDescripiton;

@property (nonatomic,strong) NSMutableArray* selectedUnitMarjorsArray; // 存放当前选择的招生单元包含专业的数组

// 大学图片相关
@property (nonatomic,strong) UIImage* image;
@property (nonatomic,strong) NSURL* imageURL;

@end

static const int ROW_HEIGHT = 50; // 设置招生单元列表中的行高
static const int PIC_HEIGHT = 200; // 大学图的高度
static const int DESCRIPTION_HEIGHT = 210; // 预留给简介的高度
static const int DESCRIPTION_TITLE_HEIGHT = 40;
static const int HEIGHT_GAP = 2; // 不同面板之间的间隔
static const int INDICATOR_WIDTH = 30; // indicator的尺寸


@implementation UniversityDetailViewController

@synthesize universityDescripiton = _universityDescripiton; // 专门为它设置这一行，否则会警告

-( NSMutableArray* ) unitsArray
{
    if( !_unitsArray ) _unitsArray = [[ NSMutableArray alloc ] init ];
    return _unitsArray;
}

-( NSMutableArray* ) selectedUnitMarjorsArray
{
    if ( !_selectedUnitMarjorsArray ) _selectedUnitMarjorsArray = [[ NSMutableArray alloc ] init ];
    return _selectedUnitMarjorsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置标题
    self.navigationItem.title = self.university.name;
    // 设置返回按钮文字
    // Set this in every view controller so that the back button displays back instead of the root view controller name
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    // 设置大学的图片
    if ( self.university ) {
        self.imageURL = [ NSURL URLWithString: [ self.university picURL ] ];
    }else{
        self.imageURL = [ NSURL URLWithString: @"http://i.bmob.cn/uploads/image/20150314/1426318889333346.jpg"];
    }
    
    // 开始下载图片
    [self startDownloadingImage];
    
    // 加载简介
    self.descripitonView.frame = CGRectMake(0, ( PIC_HEIGHT + HEIGHT_GAP ), WIDTH, DESCRIPTION_HEIGHT);
    self.universityDescripiton.frame = CGRectMake(0, DESCRIPTION_TITLE_HEIGHT, WIDTH, (DESCRIPTION_HEIGHT-DESCRIPTION_TITLE_HEIGHT-HEIGHT_GAP)); // 设置文本显示区域的尺寸
    self.universityDescripiton.text =  [NSString stringWithFormat:@"%@%@",@"       ",self.university.universityDescription];
    self.universityDescripiton.selectable = false;
     self.universityDescripiton.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    
    // 设置招生单元view
    NSUInteger tableUnitViewHeight = 100;
    if ([self.unitsArray count]) {
        tableUnitViewHeight = [self.unitsArray count] * ROW_HEIGHT + 40 ;
    };
    self.unitsView.frame = CGRectMake(0, (PIC_HEIGHT + DESCRIPTION_HEIGHT + HEIGHT_GAP), WIDTH, tableUnitViewHeight );
    self.unitTableView.frame =  CGRectMake(0, 30, WIDTH, tableUnitViewHeight );
    // 设置分割线样式
    self.unitTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.unitTableView.separatorColor = [UIColor colorWithRed:236/255.0 green:208/255.0 blue:191/255.0 alpha:1 ];
    // 禁止unitTable的滚动条
    self.unitTableView.scrollEnabled = false;
    
    // 设置滚动条
    self.scrollView.contentSize = CGSizeMake(WIDTH, PIC_HEIGHT + DESCRIPTION_HEIGHT + tableUnitViewHeight );

}


-(void) setImageURL: (NSURL*) imageURL
{
    _imageURL  = imageURL;
}

// 使用线程进行下载，防止block住用户的操作
-(void) startDownloadingImage
{
    
    self.image = nil;
    if (self.imageURL) {
        
        // 开始下载时显示等待图标
        self.indicator.frame = CGRectMake( ( WIDTH - INDICATOR_WIDTH ) / 2 , ( PIC_HEIGHT - INDICATOR_WIDTH ) / 2 , INDICATOR_WIDTH, INDICATOR_WIDTH);
        [self.indicator startAnimating]; // 让indicator 转起来
        
        NSURLRequest* request = [NSURLRequest requestWithURL:self.imageURL];
        NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession* session = [NSURLSession sessionWithConfiguration:configuration];
        // 相当于“回调函数”
        NSURLSessionDownloadTask* task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
            
            if(!error){
                if([request.URL isEqual:self.imageURL]){
                    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]]; // UIImage 比较特殊，它的创建可以不放在主线程进行
                    dispatch_async(dispatch_get_main_queue(), ^{self.image = image; }); // 调用主线程来操作设置image
                }
            }
        }];
        [task resume];
    }
}


-(UIImageView*) universityImageView
{
    if (!_universityImageView ) _universityImageView = [[UIImageView alloc] init];
    return _universityImageView;
}

-(UIImage*) image
{
    return self.universityImageView.image;
}

// 在设置图片的时候，同时调整imageView的尺寸与图片相符。
-(void)setImage:(UIImage *)image
{
    [self.indicator stopAnimating]; // 停止等待图标,注意，这个操作必须房子主线程操作，否则这句语句不会执行
    
    self.universityImageView.image = image;
    [self.universityImageView sizeToFit];
    self.universityImageView.frame = CGRectMake(0, 0, WIDTH, 200); // 固定图片的尺寸
    
    // 设置滚动视图的contentSize
//    self.scrollView.contentSize = image?image.size:CGSizeZero;
}

// 设置行高
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ROW_HEIGHT;
}

// tableView每个分区的行数，可以为各个分区设置不同的行数，根据section的值判断即可
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [ self.unitsArray count ];
}

// 实现每一行Cell的内容，tableView重用机制
static const float CELL_ARROW_X       = 280;
static const float CELL_ARROW_Y       = 15;
static const float CELL_ARROW_HEIGHT  = 20;
static const float CELL_ARROW_WIDTH   = 20;
-(UITableViewCell* ) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"cellIdentifier";
    
    UITableViewCell* cell = [ tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
    
    if ( nil == cell ) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    Unit* unit  = [ self.unitsArray objectAtIndex:indexPath.row ];
    cell.textLabel.text     = unit.name;
    NSString* tmpSubjectStr = @"选科：";
    cell.detailTextLabel.text = [ tmpSubjectStr stringByAppendingString: [ unit subjectToString ]];
    cell.detailTextLabel.textColor = [ UIColor brownColor ];
    
    // 判断如果有下属专业，则添加箭头
    if ( unit.major.length ) {
        // 设置右侧小箭头
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:[UIImage imageNamed:@"arrow_right_orange"] forState:UIControlStateNormal];
        [button setFrame:CGRectMake( CELL_ARROW_X , CELL_ARROW_Y, CELL_ARROW_WIDTH, CELL_ARROW_HEIGHT)];
        [cell.contentView addSubview:button];
    }
    
    
    return cell;
}

// 设置选中某行的处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( 0 == indexPath.section )
    {
        NSLog( @"You chosed row %lu ", indexPath.row ); //test
        Unit* unit = [self.unitsArray objectAtIndex:indexPath.row];
        if ( unit.major.length ) {
            
            // 用 majorsArray 来修改 selectedUnitMajorsArray 的内容。 注意：这里避免了重新 malloc
            [ self.selectedUnitMarjorsArray removeAllObjects ];
            for (int i = 0 ; i < [[ unit majorsArray ] count ]; i++ ) {
                [self.selectedUnitMarjorsArray addObject:[[ unit majorsArray ] objectAtIndex:i ]];
            }
            
            [ self performSegueWithIdentifier:@"universityToMajorList" sender:unit.name ];
        }
       
    }
    else
    {
        NSLog( @"You chosed section unknown " );
        
    }
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"universityToMajorList"]) {
        if ([segue.destinationViewController isKindOfClass: [MajorListViewController class]]) {
            MajorListViewController* mlVC = (MajorListViewController*)segue.destinationViewController;
            mlVC.majorsListArray = [[ NSMutableArray alloc ] initWithArray: self.selectedUnitMarjorsArray ];
            mlVC.unitTitle       = [[ NSString alloc] initWithString:sender];
            
            
        }
    }
}




@end
